<template>
  <div>
    <div class="top">{{ $t('兑换') }}</div>
    <div class="form">
      <mt-cell :title="`${$t('本 币')}`">
        <select v-model="fromIndex" class="slot1">
          <option v-for="(item, index) of fromCoinList" :key="index" :value="index"> {{ item.stock }} </option>
        </select>
        <span class="divider">{{ $t('兑换成') }}</span>
        <select v-model="toIndex" class="slot2">
          <option v-for="(item, index) of toCoinList" :key="index" :value="index"> {{ item.stock }} </option>
        </select>
      </mt-cell>
      <mt-cell
        :title="`${fromBalance.name} ${$t('余额')}`"
        :label="fromBalance.available"
      ></mt-cell>
      <mt-cell
        :title="`${toBalance.name} ${$t('余额')}`"
        :label="toBalance.available"
      ></mt-cell>
      <mt-field
        v-model="amount"
        :label="`${$t('兑换数量')}`"
        :placeholder="`${$t('请输入兑换数量')}`"
      >
        {{ fromItem.stock }}
      </mt-field>
      <mt-cell :title="`${$t('得到数量')} ≈${estimateAmount} ${toItem.stock}`">
        <span @click="tradeAll">{{ $t('全部兑换') }}</span>
      </mt-cell>
      <mt-cell
        v-if="currentCoinPair && currentOhlc"
        :title="`${$t('汇率')}`"
        :value="`1${currentCoinPair.stock} = ${currentOhlc.last}${currentCoinPair.money}`"
      ></mt-cell>
      <div class="btn-wrap">
        <mt-button
          type="primary"
          size="large"
          @click="handleSubmit"
        >
          {{ $t('兑换') }}
        </mt-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import { Button, Field, Cell, Toast, MessageBox } from 'mint-ui'
const SIDE_SELL = 1
const SIDE_BUY = 2
export default {
  components: { [Button.name]: Button, [Field.name]: Field, [Cell.name]: Cell },
  data () {
    return {
      loading: false,
      fromIndex: 0,
      toIndex: 0,
      amount: ''
    }
  },
  computed: {
    ...mapState({
      moneyList: ({ market }) => market.moneyList,
      coinPairInfo: ({ market }) => market.coinPairInfo
    }),
    ...mapGetters({
      getCoinBalance: 'fund/getCoinBalance',
      getOhlcBySymbol: 'market/getOhlcBySymbol'
    }),
    fromCoinList () {
      const list = []
      const reference = this.moneyList
      reference.forEach((stock, index) => {
        list.push({
          stock
        })
      })
      Object.keys(this.coinPairInfo).forEach((key) => {
        const item = this.coinPairInfo[key]
        if (!reference.includes(item.stock)) {
          list.push({
            stock: item.stock
          })
        }
      })
      return list
    },
    toCoinList () {
      const fromItem = this.fromCoinList[this.fromIndex]
      if (!fromItem) { return [] }
      const list = []
      Object.keys(this.coinPairInfo).forEach((key, index) => {
        const item = this.coinPairInfo[key]
        if (fromItem.stock === item.stock) {
          list.push({
            stock: item.money,
            symbol: item.name,
            side: SIDE_SELL
          })
        }
        if (fromItem.stock === item.money) {
          list.push({
            stock: item.stock,
            symbol: item.name,
            side: SIDE_BUY
          })
        }
      })
      return list
    },
    fromItem () {
      return this.fromCoinList[this.fromIndex] || {}
    },
    fromBalance () {
      const fromItem = this.fromCoinList[this.fromIndex]
      const defaultFund = { name: '', available: '0' }
      if (!fromItem) { return defaultFund }
      const coinName = fromItem.stock
      const fund = this.getCoinBalance(coinName)
      return fund || defaultFund
    },
    toItem () {
      return this.toCoinList[this.toIndex] || {}
    },
    toBalance () {
      const toItem = this.toCoinList[this.toIndex]
      const defaultFund = { name: '', available: '0' }
      if (!toItem) { return defaultFund }
      const coinName = toItem.stock
      const fund = this.getCoinBalance(coinName)
      return fund || defaultFund
    },
    currentCoinPair () {
      const toItem = this.toCoinList[this.toIndex]
      return toItem ? this.coinPairInfo[toItem.symbol] : null
    },
    currentOhlc () {
      const toItem = this.toCoinList[this.toIndex]
      return toItem ? this.getOhlcBySymbol(toItem.symbol) : null
    },
    estimateAmount () {
      if (this.currentOhlc && this.amount > 0) {
        if (this.toItem.side === SIDE_BUY) {
          return 1 * this.amount / this.currentOhlc.last
        }
        if (this.toItem.side === SIDE_SELL) {
          return 1 * this.amount * this.currentOhlc.last
        }
      }
      return 0
    }
  },
  watch: {
    fromIndex () {
      this.amount = ''
      this.toIndex = 0
    }
  },
  beforeMount () {
    this.getExchangeBalance()
  },
  methods: {
    ...mapActions({
      getExchangeBalance: 'fund/getExchangeBalance',
      createOrder: 'exchange/createOrder'
    }),
    tradeAll () {
      this.amount = this.fromBalance.available
    },
    handleSubmit () {
      if (this.amount <= 0) {
        Toast(this.$t('请输入兑换数量'))
        return
      }
      if (1 * this.amount > this.fromBalance.available) {
        Toast('兑换数量超过余额数量')
        return
      }

      MessageBox({
        title: this.$t('提示'),
        message: this.$t('确定要兑换吗？'),
        confirmButtonText: this.$t('确认'),
        showCancelButton: true,
        cancelButtonText: this.$t('取消')
      }).then((action) => {
        if (action === 'confirm') {
          this.handleOrder()
        }
      })
    },
    handleOrder () {
      if (!this.toItem.symbol) {
        Toast('数据缺失无法兑换')
        return
      }
      if (this.loading) { return }
      // 市价交易
      const payload = {
        market: this.toItem.symbol,
        side: this.toItem.side,
        pride: 0,
        amount: this.amount,
        type: 2
      }
      const succeed = () => {
        this.loading = false
        this.getExchangeBalance()
        Toast(this.$t('下单成功'))
      }
      const failed = (err) => {
        this.loading = false
        Toast(err.message)
      }
      this.loading = true
      this.createOrder(payload)
        .then(succeed)
        .catch(failed)
    }
  }
}
</script>
<style>
.mint-button-text {
  color: white !important;
}
.mint-msgbox-message {
  font-size: 14px;
}
</style>
<style scoped>
.btn-wrap {
  padding: 10px;
}
.slot1, .slot2 {
  width: 70px;
  height: 40px;
}
.divider {
  margin-left: 10px;
  margin-right: 10px;
}
</style>
